package com.example.serverdemo.controller;

import cn.hutool.json.JSONUtil;
import com.example.serverdemo.common.WisStatusCode;
import com.example.serverdemo.constant.SResType;
import com.example.serverdemo.constant.SType;
import com.example.serverdemo.constant.ServerConstant;
import com.example.serverdemo.controller.base.BaseResult;
import com.example.serverdemo.controller.vo.ChangePwdVo;
import com.example.serverdemo.controller.vo.LoginVo;
import com.example.serverdemo.service.UserService;
import com.example.serverdemo.service.dto.Denglu1Result;
import com.example.serverdemo.storage.entity.UserEntity;
import com.example.serverdemo.util.EncryptUtil;
import com.example.serverdemo.util.MySessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: liyanfeng
 * @date: 2022/3/23 23:02
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /***
     * 重定向，获取登录易登录二维码
     * @return: java.lang.String
     **/
    @GetMapping("/login")
    public String login() {
        String redirectUrl = "https://qrconnect.denglu.net.cn/connect.php?sAppId=" +
                ServerConstant.appid +
                "&sUrl=" +
                ServerConstant.context +
                "&sType=" +
                SType.login +
                "&sResType=" +
                SResType.web;
        return "redirect:" + redirectUrl;
    }

    /**
     * 应用的登录地址，进行解密验证的操作
     * @param request:
     * @param params:
     * @return: java.lang.String
     **/
    @PostMapping(value = "/login",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String login(HttpServletRequest request, @RequestParam Map<String, String> params) {

        Denglu1Result result = new Denglu1Result();
        LoginVo loginVo = JSONUtil.toBean(JSONUtil.toJsonStr(params), LoginVo.class);
        System.out.println(loginVo);
        try {
            loginVo.setSPassword(EncryptUtil.rsa_aes_decrypt(loginVo.getSPassword(), loginVo.getSEncryptedAESKey()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setICode((long) -800);
            result.setSMsg("解密password时出现错误");
            return JSONUtil.toJsonStr(result);
        }

        UserEntity user = userService.getUser(loginVo.getSUserName());

        if (user != null) {
            log.info("user:", user);
            if (user.getSPwd().equals(loginVo.getSPassword())) {
                String sessionId = request.getSession().getId();
                // 用户登录态保存，比如存入session或者redis
                HttpSession session = request.getSession();
                session.setAttribute("sUserName", loginVo.getSUserName());
                result.setICode(0L);
                result.setSMsg("SUCCESS");
                result.setSToken(sessionId);
            } else {
                result.setICode((long) -800);
                result.setSMsg("账号名或密码错误");
            }
        } else {
            result.setICode((long) -800);
            result.setSMsg("账号名或密码错误");
        }

        return JSONUtil.toJsonStr(result);
    }

    /**
     * 登录重定向地址
     * @param params
     * @return
     */
    @GetMapping(value = "/login/redirect",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public BaseResult loginRedirect( @RequestParam Map<String, String> params){
        String sToken = params.get("sToken");
        System.out.println("sToken:"+sToken);

        // 根据 sessionId 获取 session
        MySessionContext myc = MySessionContext.getInstance();
        HttpSession session = myc.getSession(sToken);

        if (session != null) {
            return BaseResult.success("重定向成功，当前用户名是: " +  session.getAttribute("sUserName"));
        } else {
            return BaseResult.fail(WisStatusCode.UNAUTHORIZED,"重定向失败，当前用户名未登录！");
        }
    }

    /***
     * 重定向，获取登录易注册二维码
     * @return: java.lang.String
     **/
    @GetMapping("/register")
    public String register(){
        String redirectUrl = "https://qrconnect.denglu.net.cn/connect.php?sAppId=" +
                ServerConstant.appid +
                "&sUrl=" +
                ServerConstant.context +
                "&sType=" +
                SType.register +
                "&sResType=" +
                SResType.web;
        return "redirect:" + redirectUrl;
    }

    /**
     * 应用的注册地址: 解密后存储都三方数据库中
     * @param request
     * @param params
     * @return
     */
    @PostMapping(value = "/register",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String register(HttpServletRequest request, @RequestParam Map<String, String> params){
        Denglu1Result result = new Denglu1Result();
        LoginVo loginVo = JSONUtil.toBean(JSONUtil.toJsonStr(params), LoginVo.class);
        System.out.println(loginVo);
        try {
            loginVo.setSPassword(EncryptUtil.rsa_aes_decrypt(loginVo.getSPassword(), loginVo.getSEncryptedAESKey()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setICode((long) -800);
            result.setSMsg("解密password时出现错误");
            return JSONUtil.toJsonStr(result);
        }
        UserEntity user = userService.getUser(loginVo.getSUserName());

        if (user == null) {
            UserEntity userEntity = new UserEntity();
            userEntity.setSUserName(loginVo.getSUserName());
            userEntity.setSPwd(loginVo.getSPassword());
            userService.save(userEntity);
            String sessionId = request.getSession().getId();
            // 用户登录态保存，比如存入session或者redis
            HttpSession session = request.getSession();
            session.setAttribute("sUserName", loginVo.getSUserName());
            result.setICode(0L);
            result.setSMsg("SUCCESS");
            result.setSToken(sessionId);
        } else {
            result.setICode((long) -801);
            result.setSMsg("用户已存在");
        }
        return JSONUtil.toJsonStr(result);
    }

    /***
     * 重定向，获取登录易修改密码二维码
     * @return: java.lang.String
     **/
    @GetMapping("/password")
    public String changePwd(){
        String redirectUrl = "https://qrconnect.denglu.net.cn/connect.php?sAppId=" +
                ServerConstant.appid +
                "&sUrl=" +
                ServerConstant.context +
                "&sType=" +
                SType.change_psw +
                "&sResType=" +
                SResType.web;
        return "redirect:" + redirectUrl;
    }

    /**
     * 应用的改密地址
     * @param request
     * @param params
     * @return
     */
    @PostMapping(value = "/password",
            consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String changePwd(HttpServletRequest request, @RequestParam Map<String, String> params){
        Denglu1Result result = new Denglu1Result();
        ChangePwdVo changePwdVo = JSONUtil.toBean(JSONUtil.toJsonStr(params), ChangePwdVo.class);
        System.out.println(changePwdVo);
        try {
            changePwdVo.setSOldPassword(EncryptUtil.rsa_aes_decrypt(changePwdVo.getSOldPassword(), changePwdVo.getSEncryptedAESKey()));
            changePwdVo.setSNewPassword(EncryptUtil.rsa_aes_decrypt(changePwdVo.getSNewPassword(), changePwdVo.getSEncryptedAESKey()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setICode((long) -800);
            result.setSMsg("解密password时出现错误");
            return JSONUtil.toJsonStr(result);
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setSUserName(changePwdVo.getSUserName());
        userEntity.setSPwd(changePwdVo.getSOldPassword());
        UserEntity user = userService.getUser(userEntity);

        if (user != null) {
            userEntity.setSPwd(changePwdVo.getSNewPassword());
            System.out.println("changePwdVo.getSNewPassword():"+changePwdVo.getSNewPassword());
            userService.update(userEntity);
            String sessionId = request.getSession().getId();
            // 用户登录态保存，比如存入session或者redis
            HttpSession session = request.getSession();
            session.setAttribute("sUserName", changePwdVo.getSUserName());
            result.setICode(0L);
            result.setSMsg("SUCCESS");
            result.setSToken(sessionId);
        } else {
            result.setICode((long) -800);
            result.setSMsg("修改密码错误");
        }
        return JSONUtil.toJsonStr(result);

    }
}
